from fabric import Connection
from deploy_script.modules.config import SysConfig
from deploy_script.logger_handler import Logger


class BaseConfigHandler:

    def __init__(self, _host_config):
        self.host_config = _host_config
        self.connection = Connection(self.host_config.ip, self.host_config.user,
                                     connect_kwargs={'password': self.host_config.password}, connect_timeout=5)

    def host_name(self):
        res = self.connection.run(
            "sed -i 's/HOSTNAME=localhost.localdomain/HOSTNAME=" + self.host_config.host + "/g' /etc/sysconfig/network")
        if res.ok:
            Logger.debug("修改ip:%s的主机名为:%s 修改文件:/etc/sysconfig/network", self.host_config.ip, self.host_config.host)
            return res.ok

    def add_hosts(self):
        configList = SysConfig.get_base_config_list()
        etc_host = ""
        for config in configList:
            etc_host += config.ip + "\\t" + config.host + "\\n"
        res = self.connection.run("sed -i '$a\\" + etc_host + "' /etc/hosts")
        Logger.debug("追加hosts文件")
        return res.ok

    def stop_firewall(self):
        res1 = self.connection.run('service iptables stop')
        if res1.ok:
            Logger.debug("关闭防火墙成功!")
        res2 = self.connection.run("sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config")
        if res2.ok:
            Logger.debug("SELINUX禁用成功!")
        return res1.ok and res2.ok

    def disable_ipv6(self):
        res1 = self.connection.run('echo "alias net-pf-10 off" >> /etc/modprobe.d/dist.conf')
        res2 = self.connection.run('echo "alias ipv6 off" >> /etc/modprobe.d/dist.conf')
        if res1.ok and res2.ok:
            Logger.debug("ipv6禁用成功!")
        return res1.ok and res2.ok

    def disable_huge_page(self):
        res1_1 = self.connection.run('echo never > /sys/kernel/mm/transparent_hugepage/defrag')
        res1_2 = self.connection.run('echo never > /sys/kernel/mm/transparent_hugepage/enabled')
        res2_1 = self.connection.run("echo 'echo never > /sys/kernel/mm/transparent_hugepage/defrag' >> /etc/rc.local")
        res2_2 = self.connection.run("echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.local")
        if res1_1.ok and res1_2.ok and res2_1.ok and res2_2.ok:
            Logger.debug("hugepage禁用成功!")
        return res1_1.ok and res1_2.ok and res2_1.ok and res2_2.ok

    def modify_swappiness(self):
        res1 = self.connection.run('sysctl vm.swappiness=10')
        res2 = self.connection.run('echo "vm.swappiness=10" >> /etc/sysctl.conf')
        if res1.ok and res2.ok:
            Logger.debug("swapiness已修改为10")
        return res1.ok and res2.ok

    def reboot(self):
        self.connection.run("reboot")

    # def do_appointed_task(self, task_name):
    #   res = self.task_dict[task_name]()
    #  return res

    def do_handle(self):
        try:
            res = self.host_name() and self.add_hosts() and self.stop_firewall() and self.disable_ipv6() \
                  and self.disable_huge_page() and self.modify_swappiness() and self.reboot()
            if res:
                Logger.info("{}基础配置修改成功".format(self.host_config.host))
            else:
                Logger.error("{}基础配置修改失败".format(self.host_config.host))
        except Exception as e:
            Logger.exception("%s基础配置修改失败,%s", self.host_config.host, e)


if __name__ == '__main__':
    list = SysConfig.get_base_config_list()
    for i in list:
        base = BaseConfigHandler(i)
        base.do_handle()
